package com.starhub.domain.annotate.component;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.starhub.domain.annotate.annotation.DataFormatAnno;
import com.starhub.domain.annotate.client.DataFormatClient;
import com.starhub.domain.annotate.enums.FormatDataEnums;

import jakarta.annotation.PostConstruct;

/**
 * 数据格式化组件
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-19
 */
@Component  
public class FormatComponent implements ApplicationContextAware {  

    private ApplicationContext applicationContext;  
    
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
        this.applicationContext = applicationContext;  
    } 

    private final Map<FormatDataEnums, DataFormatClient> clientMap = new HashMap<>();

    @PostConstruct
    public void init() {
        // 获取所有带有CollectionClient注解的Bean
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(DataFormatAnno.class);
        
        // 将Bean按照类型放入Map中
        beans.forEach((name, bean) -> {
            if (bean instanceof DataFormatClient) {
                DataFormatAnno annotation = bean.getClass().getAnnotation(DataFormatAnno.class);
                clientMap.put(annotation.value(), (DataFormatClient) bean);
            }
        });
    }

    /**
     * 根据类型获取客户端
     * @param type 知识库表类型
     * @return 对应的客户端实现
     */
    public DataFormatClient getClient(FormatDataEnums type) {
        DataFormatClient client = clientMap.get(type);
        if (client == null) {
            throw new IllegalArgumentException("Unsupported collection type: " + type);
        }
        return client;
    }
}
